package com.css.openapi.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

/**
 * 平台接入时 SM4加解密工具类
 *
 * @author xlw
 * @date 2025/09/11
 */
@Slf4j
public class SM4AccessTools {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private String secretKey;

    private String sm4Iv = "F8687C1D80B83EEE45AF23E3202024FE";

    public SM4AccessTools(String secretKey) {
        this.secretKey = secretKey;
    }

    public String encByCustom(String clear) throws Exception {
        if (StringUtils.isBlank(clear)) return clear;
        byte[] iv = Hex.decode(sm4Iv);
        byte[] encryptRet = sm4(clear.getBytes(), Hex.decode(secretKey.getBytes()), SM4ModeAndPaddingEnum.SM4_CBC_PKCS5Padding, iv, Cipher.ENCRYPT_MODE);
        return Hex.toHexString(encryptRet);
    }

    public String decByCustom(String cipher) throws Exception {
        if (StringUtils.isBlank(cipher)) return cipher;
        byte[] iv = Hex.decode(sm4Iv);
        byte[] decryptRet = sm4(Hex.decode(cipher.getBytes()), Hex.decode(secretKey.getBytes()), SM4ModeAndPaddingEnum.SM4_CBC_PKCS5Padding, iv, Cipher.DECRYPT_MODE);
        return new String(decryptRet);
    }

    private static byte[] sm4(byte[] input, byte[] key, SM4ModeAndPaddingEnum sm4ModeAndPaddingEnum, byte[] iv, int mode) throws Exception {
        IvParameterSpec ivParameterSpec = null;
        if (iv != null) {
            ivParameterSpec = new IvParameterSpec(iv);
        }
        SecretKeySpec sm4Key = new SecretKeySpec(key, "SM4");
        Cipher cipher = Cipher.getInstance(sm4ModeAndPaddingEnum.getName(), BouncyCastleProvider.PROVIDER_NAME);
        if (ivParameterSpec == null) {
            cipher.init(mode, sm4Key);
        } else {
            cipher.init(mode, sm4Key, ivParameterSpec);
        }
        return cipher.doFinal(input);
    }

    // 加密
    public static String encryptEcb_PKCS7_Padding(String hexKey, String paramStr, String charset) {
        try {
            String cipherText = "";
            if (null != paramStr && !"".equals(paramStr)) {
                byte[] keyData = ByteUtils.fromHexString(hexKey);
                if (StringUtils.isBlank(charset)) charset = "UTF-8";
                byte[] srcData = paramStr.getBytes(charset);
                byte[] cipherArray = encrypt_Ecb_PKCS7_Padding(keyData, srcData);
                cipherText = ByteUtils.toHexString(cipherArray);
            }
            return cipherText;
        } catch (Exception e) {
            log.error("Sm4加密失败", e);
            return null;
        }
    }

    // 加密模式之ecb
    private static byte[] encrypt_Ecb_PKCS7_Padding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher("SM4/ECB/PKCS7Padding", Cipher.ENCRYPT_MODE, key);
        byte[] bs = cipher.doFinal(data);
        return bs;
    }


    // Sm4解密
    public static String decryptEcb_PKCS7_Padding(String hexKey, String cipherText, String charset) {
        try {
            String decryptStr = "";
            byte[] keyData = ByteUtils.fromHexString(hexKey);
            byte[] cipherData = ByteUtils.fromHexString(cipherText);
            byte[] srcData = decrypt_Ecb_PKCS7_Padding(keyData, cipherData);
            if (StringUtils.isBlank(charset)) charset = "UTF-8";
            decryptStr = new String(srcData, charset);
            return decryptStr;
        } catch (Exception e) {
            log.error("Sm4解密失败", e);
            return null;
        }
    }

    // 解密
    private static byte[] decrypt_Ecb_PKCS7_Padding(byte[] key, byte[] cipherText) throws Exception {
        Cipher cipher = generateEcbCipher("SM4/ECB/PKCS7Padding", Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }


    // 生成ecb暗号
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, "SM4");
        cipher.init(mode, sm4Key);
        return cipher;
    }

}
